package com.atguigu.gulimail.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.gulimail.search.config.GulimailElasticSearchConfig;
import com.atguigu.gulimail.search.constant.EsConstant;
import com.atguigu.gulimail.search.service.MailSearchService;
import com.atguigu.gulimail.search.vo.SearchParam;
import com.atguigu.gulimail.search.vo.SearchResult;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Guo 2022/11/2 16:19:37
 */
@Service
@Slf4j
public class MailSearchServiceImpl implements MailSearchService {

    @Autowired
    private RestHighLevelClient client;

    /**
     * 通过检索条件返回相应的结果
     * 去ES进行检索
     *
     * @param param 检索的所有条件
     * @return
     */
    @Override
    public SearchResult search(SearchParam param) {
        // 动态的构建出查询需要的DSL语句
        SearchResult result = null;
        // 1、准备检索请求
        SearchRequest searchRequest = buildSearchRequest(param);
        try {
            // 2、执行检索请求
            SearchResponse response = client.search(searchRequest, GulimailElasticSearchConfig.COMMON_OPTIONS);
            // 3、分析响应数据，并封装成我们需要的格式
            result = buildSearchResult(response, param);
        } catch (IOException e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return result;
    }

    /**
     * 准备检索请求
     * 模糊匹配、过滤(按照属性，分类，品牌，价格区间，库存) | 页码、高亮、排序 | 聚合分析
     *
     * @return
     */
    private SearchRequest buildSearchRequest(SearchParam param) {
        // SearchSourceBuilder 用来构建DSL语句
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        /**
         * 查询：模糊匹配、过滤(按照属性，分类，品牌，价格区间，库存)
         */
        // 1、构建bool - query
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // 1.1 must 模糊匹配
        if (StringUtils.isNotEmpty(param.getKeyword())) {
            boolQuery.must(QueryBuilders.matchQuery("skuTitle", param.getKeyword()));
        }
        // 1.2.1 bool - filter 按照三级分类ID查询
        if (ObjectUtils.isNotEmpty(param.getCatalog3Id())) {
            boolQuery.filter(QueryBuilders.termQuery("catalogId", param.getCatalog3Id()));
        }
        // 1.2.2 bool - filter 按照所有品牌ID(List<Long>)查询
        if (CollectionUtils.isNotEmpty(param.getBrandId())) {
            boolQuery.filter(QueryBuilders.termsQuery("brandId", param.getBrandId()));
        }
        // 1.2.3 bool - filter 按照所有指定的属性查询
        if (CollectionUtils.isNotEmpty(param.getAttrs())) {
            for (String attrStr : param.getAttrs()) {
                // attrs=1_其他:苹果ios&attrs=2_5寸:6寸
                BoolQueryBuilder nestedBoolQuery = QueryBuilders.boolQuery();
                // attr -- 1_其他:苹果  -- 2_5寸:6寸
                String[] s = attrStr.split("_");
                String attrId = s[0];  // 检索的属性id
                String[] attrValue = s[1].split(":"); // 检索的所有属性值
                nestedBoolQuery.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                nestedBoolQuery.must(QueryBuilders.termsQuery("attrs.attrValue", attrValue));
                // attrs在ES中的类型是一个嵌入式nested的。
                /**
                 * 关键点：
                 * 每一个从页面传来的属性都必须生成自己的一个nested查询
                 */
                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", nestedBoolQuery, ScoreMode.None);
                boolQuery.filter(nestedQuery);
            }
        }
        // 1.2.4 bool - filter 按照是否有库存进行查询
        if (ObjectUtils.isNotNull(param.getHasStock())) {
            boolQuery.filter(QueryBuilders.termQuery("hasStock", param.getHasStock() == 1));
        }
        // 1.2.4 bool - filter 按照价格区间进行检索
        if (StringUtils.isNotEmpty(param.getSkuPrice())) {
            /**
             * skuPrice=1_500/_500/500_
             * "range": {
             *             "skuPrice": {
             *               "gte": 0,
             *               "lte": 6000
             *             }
             *           }
             */
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
            String[] split = param.getSkuPrice().split("_");
            if (split.length == 2) {
                // 区间
                rangeQuery.gte(split[0]).lte(split[1]);
            } else if (split.length == 1) {
                // 大于/小于 某个值
                if (param.getSkuPrice().startsWith("_")) {
                    rangeQuery.lte(split[0]);
                }
                if (param.getSkuPrice().endsWith("_")) {
                    rangeQuery.gte(split[0]);
                }
            }
            boolQuery.filter(rangeQuery);
        }
        // 把以前所有的查询条件都拿来封装
        sourceBuilder.query(boolQuery);

        /**
         * 页码、高亮、排序
         */
        // 2.1、排序 sort=saleCount_asc/desc
        if (StringUtils.isNotEmpty(param.getSort())) {
            String[] s = param.getSort().split("_");
            SortOrder sortOrder = s[1].equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC;
            sourceBuilder.sort(s[0], sortOrder);
        }
        // 2.2 分页
        /**
         * pageSize = 5
         * pageNum:1 -- from:0 -- size:5 -- [0,1,2,3,4]
         * pageNum:2 -- from:5 -- size:5 -- [5,6,7,8,9]
         * from = (pageNum - 1) * size
         */
        sourceBuilder.from((param.getPageNum() - 1) * EsConstant.PRODUCT_PAGESIZE);
        sourceBuilder.size(EsConstant.PRODUCT_PAGESIZE);
        // 2.3 高亮 highLight 有通过keyword进行全文模糊匹配的才有必要进行高亮显示
        if (StringUtils.isNotEmpty(param.getKeyword())) {
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");
            sourceBuilder.highlighter(highlightBuilder);
        }
        /**
         * 聚合分析  -- 品牌、分类、属性
         * 无需条件，所有被检索的属性都要加
         */
        // 3.1 品牌brand聚合
        TermsAggregationBuilder brandAgg = AggregationBuilders.terms("brand_agg").field("brandId").size(50);
        // 3.1.1 品牌聚合的子聚合
        brandAgg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName")).size(50);
        brandAgg.subAggregation(AggregationBuilders.terms("brand_image_agg").field("brandImg")).size(50);
        sourceBuilder.aggregation(brandAgg);
        // 3.2 分类catelog聚合
        TermsAggregationBuilder catelogAgg = AggregationBuilders.terms("catelog_agg");
        catelogAgg.field("catalogId").size(50);
        // 3.2.2 分类聚合的子聚合
        catelogAgg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName")).size(50);
        sourceBuilder.aggregation(catelogAgg);
        // 3.3 属性attrs聚合  -- 最外层嵌入式nested的聚合
        NestedAggregationBuilder nestedAttrAgg = AggregationBuilders.nested("attr_agg", "attrs");
        // 3.3.1 先聚合出所有的attrId
        TermsAggregationBuilder attrIdAgg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId").size(50);
        // 3.3.2 子聚合分析出当前attrId所对应的名字和值
        attrIdAgg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName")).size(1);
        attrIdAgg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue")).size(50);
        // 3.3.3 这个是把attrIdAgg塞到最外层的嵌入式nestedAttrAgg中
        nestedAttrAgg.subAggregation(attrIdAgg);
        sourceBuilder.aggregation(nestedAttrAgg);


        String s = sourceBuilder.toString();
        log.info("构建出的DSL语句" + s);
        // 检索条件封装到SearchRequest中
        SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, sourceBuilder);
        return searchRequest;
    }

    /**
     * 构建结果数据
     *
     * @param response
     * @return
     */
    private SearchResult buildSearchResult(SearchResponse response, SearchParam param) {

        SearchResult result = new SearchResult();
        /**
         * 查询信息
         */
        // 1、返回的所有查询到的商品
        SearchHits hits = response.getHits();
        List<SkuEsModel> esModels = new ArrayList<>();
        if (ObjectUtils.isNotEmpty(hits)) {
            for (SearchHit hit : hits.getHits()) {
                String sourceAsString = hit.getSourceAsString();
                SkuEsModel esModel = JSON.parseObject(sourceAsString, SkuEsModel.class);
                if (StringUtils.isNotEmpty(param.getKeyword())) {
                    // 高亮文字设置
                    HighlightField highlightField = hit.getHighlightFields().get("skuTitle");
                    String skuTitle = highlightField.getFragments()[0].toString();
                    esModel.setSkuTitle(skuTitle);
                }
                esModels.add(esModel);
            }
        }
        result.setProducts(esModels);
        /**
         * 聚合信息
         */
        // 2、1 当前所有商品涉及到的属性信息
        ParsedNested attrAgg = response.getAggregations().get("attr_agg");
        List<SearchResult.AttrVo> attrVos = new ArrayList<>();
        ParsedLongTerms attrIdAgg = attrAgg.getAggregations().get("attr_id_agg");
        for (Terms.Bucket bucket : attrIdAgg.getBuckets()) {
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            // 1、得到属性的id
            long attrId = bucket.getKeyAsNumber().longValue();
            // 2、得到属性的名字
            String attrName = ((ParsedStringTerms) bucket.getAggregations().get("attr_name_agg")).getBuckets().get(0).getKeyAsString();
            // 3、得到属性的值 -- 1个名字可以对应多个值
            List<String> attrValues = ((ParsedStringTerms) bucket.getAggregations().get("attr_value_agg")).getBuckets().stream().map(MultiBucketsAggregation.Bucket::getKeyAsString).collect(Collectors.toList());
            attrVo.setAttrId(attrId);
            attrVo.setAttrName(attrName);
            attrVo.setAttrValue(attrValues);
            attrVos.add(attrVo);
        }
        result.setAttrs(attrVos);
        // 2、2 当前所有商品涉及到的品牌信息
        ParsedLongTerms brandAgg = response.getAggregations().get("brand_agg");
        List<SearchResult.BrandVo> brandVos = new ArrayList<>();
        for (Terms.Bucket bucket : brandAgg.getBuckets()) {
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
            // 1、得到品牌ID
            brandVo.setBrandId(Long.parseLong(bucket.getKeyAsString()));
            // 2、获取品牌的名字和图片url
            String brandNameAgg = ((ParsedStringTerms) bucket.getAggregations().get("brand_name_agg")).getBuckets().get(0).getKeyAsString();
            String brandImageAgg = ((ParsedStringTerms) bucket.getAggregations().get("brand_image_agg")).getBuckets().get(0).getKeyAsString();
            brandVo.setBrandName(brandNameAgg);
            brandVo.setBrandImg(brandImageAgg);
            brandVos.add(brandVo);
        }
        result.setBrands(brandVos);
        // 2、3 当前所有商品涉及到的分类信息
        ParsedLongTerms catelogAgg = response.getAggregations().get("catelog_agg");
        List<SearchResult.CatalogVo> catalogVos = new ArrayList<>();
        List<? extends Terms.Bucket> catelogAggBuckets = catelogAgg.getBuckets();
        for (Terms.Bucket bucket : catelogAggBuckets) {
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
            String keyAsString = bucket.getKeyAsString();
            // 得到分类ID
            catalogVo.setCatalogId(Long.parseLong(keyAsString));
            // 得到分类名字 -- 获取子聚合
            ParsedStringTerms catalogNameAgg = bucket.getAggregations().get("catalog_name_agg");
            String catalogName = catalogNameAgg.getBuckets().get(0).getKeyAsString();
            catalogVo.setCatalogName(catalogName);
            catalogVos.add(catalogVo);
        }
        result.setCatalogs(catalogVos);
        /**
         * 分页信息
         */
        // 3、1 分页信息 - 页码
        result.setPageNum(param.getPageNum());
        // 3、2 分页信息 - 总记录数
        long total = hits.getTotalHits().value;
        result.setTotal(total);
        // 3、3 分页信息 - 总页码 -- 计算得到  eg:总记录数11 / 每页显示数量2 = 5 ... 1
        int totalPages = (int) total % EsConstant.PRODUCT_PAGESIZE == 0 ? (int) total / EsConstant.PRODUCT_PAGESIZE : (int) (total / EsConstant.PRODUCT_PAGESIZE + 1);
        result.setTotalPages(totalPages);

        // 3、4 可遍历的分页数组信息
        List<Integer> pageNavs = new ArrayList<>();
        for (int i = 1; i <= totalPages; i++) {
            pageNavs.add(i);
        }
        result.setPageNavs(pageNavs);

        return result;
    }


}
